import { handleActions as createReducer } from 'redux-actions'
import { addProductToLocalCart, changeLocalProductCount, deleteLocalCarts, saveCarts } from '../actions/cart.actions'

const initialState = {
  carts: []
}

export default createReducer({
  // 添加商品
  [addProductToLocalCart]: (state, action) => {
    // 不进行深拷贝 将不会重新渲染
    const newState = JSON.parse(JSON.stringify(state.carts))
    // 判断商品是否存在于 carts
    const product = newState.find(product => product.id === action.payload.id)
    if (product) {
      product.count ++
    } else {
      newState.push(action.payload)
    }
    return {carts: newState}
  },
  // 获取商品
  [saveCarts]: (state, action) => ({carts: action.payload}),
  // 删除商品
  [deleteLocalCarts]: (state, action) => {
    const newState = JSON.parse(JSON.stringify(state.carts))
    const index = newState.findIndex(product => product.id === action.payload)
    newState.splice(index, 1)
    return {
      carts: newState
    }
  },
  // 修改商品数量
  [changeLocalProductCount]: (state, action) => {
    const newState = JSON.parse(JSON.stringify(state.carts))
    const product = newState.find(product => product.id === action.payload.id)
    if (product) {
      product.count = action.payload.count
    }
    return {
      carts: newState
    }
  }
}, initialState)